package com.hmz.backend.filter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmz.backend.entity.User;
import com.hmz.backend.mapper.UserMapper;
import com.hmz.backend.utils.PasswordEncoder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class MyInterceptor implements HandlerInterceptor {
    @Autowired
    UserMapper userMapper;
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        String url = httpServletRequest.getRequestURI(); //获取请求的url
        System.out.println(url);
        //放行OPTIONS请求
        if ("OPTIONS".equals(httpServletRequest.getMethod())) return true;
        if(url.contains("/test")) return true;// 放行注册请求
        if(url.contains("/login")) return true; //放行登录请求
        if(url.contains("/register")) return true; //放行注册请求
        if(url.contains("/getnotice"))return true; //放行获取公告请求
        if(url.contains("/getAvatar")) return true;// 获取头像请求放行
        if(url.contains("/getMessageImg")) return true; //获取图片消息请求放行
        if(url.contains("/error")) return false;
        else {
            //测试记得删
            if(httpServletRequest.getHeader("Authorization").equals("test")) return true;
            String token = "";
            //如果是websocket请求的话
            if(url.contains("/chat")){
                String[] pathParts = url.split("/"); //通过分割/来得到参数列表
                token = pathParts[1]; //得到websocket得token
            }
            else if (!httpServletRequest.getHeader("Authorization").startsWith("hmz ")) return false; //其余得请求必须携带Authorization这个请求头
            if(token.isEmpty()) token = httpServletRequest.getHeader("Authorization").substring(4);
            String uncode = PasswordEncoder.uncode(token); //对token进行解码
            int userId = Integer.parseInt(uncode.substring(4)); //从token获取userId
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",userId);
            int userType = userMapper.selectOne(queryWrapper).getUserType(); //根据用户Id获取用户类型
            if (url.contains("/sendnotice") && userType == 0)  return false; //如果访问发公告的接口
            else if (uncode.contains("user") || userType == 1) return true; //检验解码后是否结果是否正常
            else return false;
        }

    }
}
